package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.repository.MakeMoneyTableRepository;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.vo.MakeMoneyTableVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2015-5-15下午06:46:35
 * 类的说明：前端APIMakeMoneyTable接口实现类
 **/
@Service("ApiMakeMoneyTableService")
@Transactional(readOnly = false)
public class ApiMakeMoneyTableServiceImpl extends BaseService<MakeMoneyTable> implements ApiMakeMoneyTableService {

    private static final Logger LOGGER = Logger.getLogger(ApiMakeMoneyTableServiceImpl.class);

    @Autowired
    MakeMoneyTableRepository makeMoneyTableRepository;

    @Override
    public XaResult<MakeMoneyTableVo> findOne(Long tId) throws BusinessException {
        MakeMoneyTable obj = makeMoneyTableRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<MakeMoneyTableVo> xr = new XaResult<MakeMoneyTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MakeMoneyTableVo.class));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->MakeMoneyTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<List<MakeMoneyTableVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<MakeMoneyTable> page = makeMoneyTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), MakeMoneyTable.class), pageable);
        XaResult<List<MakeMoneyTableVo>> xr = new XaResult<List<MakeMoneyTableVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), MakeMoneyTableVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<List<MakeMoneyTableVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<MakeMoneyTable> page = makeMoneyTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), MakeMoneyTable.class), pageable);
        XaResult<List<MakeMoneyTableVo>> xr = new XaResult<List<MakeMoneyTableVo>>();
        List<MakeMoneyTable> vos = new ArrayList<MakeMoneyTable>();
        MakeMoneyTable obj;
        for (int i = 0; i < page.getContent().size(); i++) {
            if (page.getContent().get(i) != null) {
                obj = makeMoneyTableRepository.findOne(page.getContent().get(i).getId());
                obj.setId(obj.getId());
                obj.setConsumeOrMakeMoney(obj.getConsumeOrMakeMoney());
                obj.setCreateTime(obj.getCreateTime());
                obj.setMakeMoney_Cost(obj.getMakeMoney_Cost());
                obj.setType(obj.getType());
                obj.setUserId(obj.getUserId());
                vos.add(obj);
            }
        }
        xr.setObject(JSON.parseArray(JSON.toJSONString(vos), MakeMoneyTableVo.class));
        return xr;
    }

    @Override
    public XaResult<MakeMoneyTableVo> multiOperate(String modelIds,
                                                   Integer status) throws BusinessException {
        XaResult<MakeMoneyTableVo> xr = new XaResult<MakeMoneyTableVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                MakeMoneyTable obj = makeMoneyTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = makeMoneyTableRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MakeMoneyTableVo.class));
                    xr.getObject().setId(obj.getId());
                }
            }
        }
        LOGGER.info("更改数据状态----->MakeMoneyTable");
        return xr;
    }

    @Override
    public XaResult<MakeMoneyTableVo> createModel(MakeMoneyTable model)
            throws BusinessException {
        XaResult<MakeMoneyTableVo> xr = new XaResult<MakeMoneyTableVo>();
        MakeMoneyTable obj = makeMoneyTableRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MakeMoneyTableVo.class));
        xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->MakeMoneyTable");
        return xr;
    }

    @Override
    public XaResult<MakeMoneyTableVo> updateModel(MakeMoneyTable model)
            throws BusinessException {
        MakeMoneyTable obj = makeMoneyTableRepository.findOne(model.getId());
        XaResult<MakeMoneyTableVo> xr = new XaResult<MakeMoneyTableVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
            obj.setMakeMoney_Cost(XaUtil.isNotEmpty(model.getMakeMoney_Cost()) ? model.getMakeMoney_Cost() : obj.getMakeMoney_Cost());
            obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
            obj.setConsumeOrMakeMoney(XaUtil.isNotEmpty(model.getConsumeOrMakeMoney()) ? model.getConsumeOrMakeMoney() : obj.getConsumeOrMakeMoney());
            obj.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : obj.getOrderNo());
            obj = makeMoneyTableRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MakeMoneyTableVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error(XaConstant.Message.object_not_find);
        }
        LOGGER.info("编辑数据成功----->MakeMoneyTable");
        return xr;
    }

    /**
     * 使用或者赚钱亲币记录
     *
     * @param userId
     * @param consumeOrMakeMoney 使用 {@link JConstant.ConsumeOrMakeMoney} 的取值
     * @param type               使用 {@link JConstant.IntegralTypeEnum} 中的取值
     * @param coin
     * @return
     */
    @Override
    public XaResult<MakeMoneyTable> saveMakeMoneyRecord(long userId, int consumeOrMakeMoney, int coin, long type) {
        XaResult<MakeMoneyTable> xr = new XaResult<>();
        MakeMoneyTable makeMoneyObj = new MakeMoneyTable();
        makeMoneyObj.setType(Long.parseLong(type + ""));
        makeMoneyObj.setMakeMoney_Cost(Double.valueOf(coin));
        makeMoneyObj.setUserId(userId);
        makeMoneyObj.setConsumeOrMakeMoney(consumeOrMakeMoney);
        makeMoneyObj = makeMoneyTableRepository.save(makeMoneyObj);
        xr.setObject(makeMoneyObj);
        return xr;
    }
}
